package com.shenchuangit.webprintclient.printer;

import java.awt.*;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;

public class PngPrinter implements Printable {
    /**
     * @param gra       指明打印的图形环境
     * @param pf        指明打印页格式（页面大小以点为计量单位，1点为1英才的1/72，1英寸为25.4毫米。A4纸大致为595×842点）
     * @param pageIndex 指明页号
     **/
    @Override
    public int print(Graphics gra, PageFormat pf, int pageIndex) throws PrinterException {
        System.out.println("pageIndex=" + pageIndex);
        Component c = null;
        //print string
        String str = "中华民族是勤劳、勇敢和富有智慧的伟大民族。";
        //转换成Graphics2D
        Graphics2D g2 = (Graphics2D) gra;
        //设置打印颜色为黑色
        g2.setColor(Color.black);

        Paper paper = pf.getPaper();//得到页面格式的纸张
        paper.setSize(100, 50);//纸张大小
        paper.setImageableArea(0, 0, 100, 50); //设置打印区域的大小
        pf.setPaper(paper);//将该纸张作为格式

        //打印起点坐标
        double x = pf.getImageableX();
        double y = pf.getImageableY();

        // -1- 用Graphics2D直接输出
        //首字符的基线(右下部)位于用户空间中的 (x, y) 位置处

        //g2.drawLine(10,10,200,10);

        Image src = Toolkit.getDefaultToolkit().getImage("d://logo.gif");
        g2.drawImage(src, (int) x, (int) y, c);
        int img_Height = src.getHeight(c);
        int img_width = src.getWidth(c);
        //System.out.println("img_Height="+img_Height+"img_width="+img_width) ;

        g2.drawImage(src, (int) x, (int) (img_Height + 11), c);


        // -2- 直接构造TextLayout打印
            /*FontRenderContext frc = g2.getFontRenderContext();
            TextLayout layout = new TextLayout(str, font, frc);
            layout.draw(g2, (float)x, (float)y+2*heigth);*/
        // -3- 用LineBreakMeasurer进行打印
            /*AttributedString text = new AttributedString(str);
            text.addAttribute(TextAttribute.FONT, font);
            LineBreakMeasurer lineBreaker = new LineBreakMeasurer(text.getIterator(), frc);
            //每行字符显示长度(点)
            double width = pf.getImageableWidth();
            //首字符的基线位于用户空间中的 (x, y) 位置处
            Point2D.Double pen = new Point2D.Double (100, y+3*heigth);
            while ( (layout = lineBreaker.nextLayout( (float) width)) != null){
               layout.draw(g2, (float)x, (float) pen.y);
               pen.y += layout.getAscent();
            }*/
        return PAGE_EXISTS;
    }
}
